package com.isp.org.server.interfaces.http.menu;

import com.isp.common.model.constant.CommonConstant;
import com.isp.common.model.vo.Result;
import com.isp.org.api.dto.menu.SysMenu;
import com.isp.org.server.application.facade.MenuFacade;
import com.isp.org.server.interfaces.model.menu.vo.request.MenuCreateRequest;
import com.isp.org.server.interfaces.model.menu.vo.request.MenuToRoleRequest;
import com.isp.org.server.interfaces.model.menu.vo.request.MenuUpdateRequest;
import com.isp.org.server.interfaces.model.menu.vo.response.MenuInfoResponse;
import com.isp.org.server.interfaces.model.menu.vo.response.MenuTreeResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/1/24 17:51
 */
@Api(tags = "菜单接口")
@RestController
@RequestMapping("/menus")
@RequiredArgsConstructor
@Slf4j
public class MenuController {

    private final MenuFacade menuFacade;

    @Operation(summary = "删除菜单")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable String id) {
        try {
            menuFacade.removeById(id);
            return Result.success(true);
        } catch (Exception ex) {
            log.error("memu-delete-error", ex);
            return Result.error("操作失败");
        }
    }

    @Operation(summary = "根据roleId获取对应的菜单")
    @GetMapping("/{roleId}/menus")
    public List<Map<String, Object>> findMenusByRoleId(@PathVariable Long roleId) {
        Set<Long> roleIds = new HashSet<>();
        roleIds.add(roleId);
        //获取该角色对应的菜单
        List<SysMenu> roleMenus = menuFacade.findByRoles(roleIds);
        //全部的菜单列表
        List<SysMenu> allMenus = menuFacade.findAll();
        List<Map<String, Object>> authTrees = new ArrayList<>();
        Map<Long, SysMenu> roleMenusMap = roleMenus.stream().collect(Collectors.toMap(SysMenu::getId, SysMenu -> SysMenu));
        for (SysMenu sysMenu : allMenus) {
            Map<String, Object> authTree = new HashMap<>();
            authTree.put("id", sysMenu.getId());
            authTree.put("name", sysMenu.getName());
            authTree.put("parent_id", sysMenu.getParentId());
            authTree.put("open", true);
            authTree.put("checked", false);
            if (roleMenusMap.get(sysMenu.getId()) != null) {
                authTree.put("checked", true);
            }
            authTrees.add(authTree);
        }
        return authTrees;
    }

    @ApiOperation("根据roleCodes获取对应的权限")
    @GetMapping("/{roleCodes}")
    public List<SysMenu> findMenuByRoles(@PathVariable String roleCodes) {
        List<SysMenu> result = null;
        if (StringUtils.isNotEmpty(roleCodes)) {
            Set<String> roleSet = Arrays.stream(roleCodes.split(",")).collect(Collectors.toSet());
            result = menuFacade.findByRoleCodes(null, roleSet, CommonConstant.PERMISSION);
        }
        return result;
    }

    @ApiOperation("角色分配菜单")
    @PostMapping("/granted")
    public Result<Boolean> setMenuToRole(@RequestBody MenuToRoleRequest sysMenu) {
        menuFacade.setMenuToRole(sysMenu.getRoleId(), sysMenu.getMenuIds());
        return Result.success("操作成功", true);
    }

    @ApiOperation("查询所有菜单")
    @GetMapping()
    public Result<List<MenuInfoResponse>> pageList() {
        List<MenuInfoResponse> responses = menuFacade.pageList();
        return Result.success(responses);
    }

    @ApiOperation("获取菜单以及顶级菜单")
    @GetMapping("/findOnes")
    public Result<List<MenuInfoResponse>> findOnes() {
        List<MenuInfoResponse> responses = menuFacade.findOnes();
        return Result.success(responses);
    }

    @GetMapping("/current")
    @ApiOperation("查询当前用户菜单")
    public Result<List<MenuTreeResponse>> findMyMenu() {
        Long userId = null;
        List<MenuTreeResponse> menus = menuFacade.findTreeByUserId(userId, CommonConstant.MENU);
        return Result.success(menus);
    }

    @PostMapping("")
    @ApiOperation("创建菜单")
    public Result<Boolean> create(@RequestBody MenuCreateRequest request) {
        Boolean response = menuFacade.create(request);
        return Result.success(response);
    }

    @PutMapping("/{id}")
    @ApiOperation("更新菜单")
    public Result<Boolean> update(@PathVariable Long id, @RequestBody MenuUpdateRequest request) {

        Boolean response = menuFacade.update(id, request);
        return Result.success(response);
    }

}
